import { User } from "./user.js";

const existedUserWithName = async (name) => {
  return await User.find({name: name});
};

const allUsers = async () => {
  return await User.find({});
}

const checkUser = async (name, password) => {
  return await User.findOne({ name: name, password: password });
}

const updateUserVisits = async (name, count) => {
  return await User.updateOne({ name: name }, { $set: { visits: count }}).exec();
}

const findAllNotesByUser = async (name) => {
  let user = await User.findOne({ name: name });
  return user 
}


const addNoteByUser = async (name, title, content, tag) => {
  let note = { title: title, content: content, tag: tag };
  let user = await User.findOne({ name: name });
  user.notes.push(note);
  return await user.save();
}

const removeNoteByID = async (name, id) => {
  let user = await User.findOne({ name: name });
  console.log(id);
  console.log(user.notes);
  user.notes = user.notes.filter(note => note._id.toString() !== id);
  console.log(user.notes);
  return await user.save();
};


const modifyNoteByID = async(name, id, title, content) => {
    let user = await User.findOne({ name: name});
    user.notes.forEach(note => {
        if(note._id.toString() == id){
            note.title = title;
            note.content = content;
        }
    });
    return await user.save();
}

const findNotesByKeyword = async(name, keyword) => {
  let user = await User.findOne({ name: name});
  let notes = [];
  user.notes.forEach(note => {
    if(note.title.includes(keyword, 0) || note.content.includes(keyword, 0) || (note.tag && note.tag.includes(keyword, 0))) {
      notes.push(note);
    }
  });
  return notes;
}


export { updateUserVisits,  checkUser, allUsers, existedUserWithName, findAllNotesByUser, 
    addNoteByUser, removeNoteByID, modifyNoteByID, findNotesByKeyword }